~function() {
    // 相对日期
    function getRelativeDate(count){
        var today = new Date(),
            theDay = today;
        typeof count == 'undefined'?null:theDay.setDate(today.getDate() + count);
        return theDay
    }
    // 日期格式化 YYYY-MM-DD
    function dataToYYYYMMDD(date){
        var ss = new Date(date),
            year = ss.getFullYear(),
            month = ss.getMonth()+1 > 9?(ss.getMonth()+1).toString():'0'+(ss.getMonth()+1).toString(),
            day = ss.getDate();
        return year + '-' + month + '-' + day
    }
    // 当前用户信息
    var user = {
        isAdmin:true,//是否为管理员
        channelList:[],//当前账号列表
        curChannelId:0,//当前账号
        billList:[], //当前计费列表
        curBillId:0,  //当前计费id
        timeStart:getRelativeDate(-7),
        timeEnd:getRelativeDate(-1),
        timeStartFormatting:dataToYYYYMMDD(getRelativeDate(-7)),
        timeEndFormatting:dataToYYYYMMDD(getRelativeDate(-1)),
        //当前tab页 
        // 'byDay'/
        // 'byType'
        // 'typeDetail'
        curTab:'byDay',
        curType:""
    };
    // 数据缓存
    var dataCache = [];
    // 填充用户列表相关
    var Api = {
        getUserList:"http://ch.union-wifi.com/user/getUserList?username=sjcm&password=sjcmzmeng2016",
        getChannleList:"http://ch.union-wifi.com/channelQuery/getChannelList?dateBegin=2016-08-31&dateEnd=2016-08-31&channelId=10&billId=0",
        getChannleDetailList:"http://ch.union-wifi.com/channelQuery/getChannleDetailList"
    };
    var normoliazedFormat = {
            'isEmpty':false,    //是否为空数据
            'tableByDayList':[], // 表格数据
            'tableByDayColumn':[], // 表格数据
            'tableByTypeList':[], // 表格数据
            'tableByTypeColumn':[], // 表格数据
            'tableAdType':{},//各个广告位本段时间内总数据
            'tableAdTypeByDay':{},//各个广告位的按日数据
            'tableAdTypeByDayColumn':{},//各个广告位的按日数据标题
            'dateList':[], // 日期列表，正序排序
            'unified':{}, // 统一的数据结构
            'dashboardAdTypeByDay':{}, //广告位
            'adTypeAll':{},
            'dashboard':{
                "impressionBd":0,     //总展现
                "impressionBdAvg":0,  //日均总展现
                "clickBd":0,            //总点击
                "clickBdAvg":0,          //日均总点击 
                "clickBdRate":0,        //总点击率
                "clickBdRateAvg":0,     //日均点击率
                "ecpm":0,                //ecpm
                "ecpmAvg":0,            //日均ecpm
                "earn":0,               //收入
                "earnAvg":0            //日均收入
            }  //基础汇总tip
        };

	var zggzxl = $("#zggzxl"),
	 	rpjggzxl = $("#rpjggzxl"),
		zdjl = $("#zdjl"),
		rpjzdjl = $("#rpjzdjl"),
		zdjl2 = $("#zdjl2"),
		rpjdjl2 = $("#rpjdjl2"),
		ecpm = $("#ecpm"),
		rpjecpm = $("#rpjecpm"),
		allincome = $("#allincome"),
		rpjincome = $("#rpjincome"),
        tableByDayDom = $('#tableByDay'),
        tableByTypeDom = $('#tableByType'),
        tableTypeByDayDom = $('#tableTypeByDay'),
        tableByDayCon = $('.tableByDay'),
        tableByTypeCon = $('.tableByType'),
        tableTypeByDayCon = $('.tableTypeByDay'),
		echartContainer = $('#echartWrapper'),
        dropdownAccount = $(".dropdownAccount"),
        dropdownAccountContainer= $(".accountContainer"),
        dropdownBill = $(".dropdownBill"),
        dropdownBillContainer= $(".billContainer"),
        cproTypeNameTag = $(".cproTypeNameTag"), //广告位名称  - 文字
        defaultReport = $(".defaultReport"),
        echartNav = $(".echartNav"), //选择栏
        tableByDay = null,//按天图表
        tableByType = null,
        tableTypeByDay = null,
        echartTable = null, //echart图表对象
        tableOption = {
            // "autoWidth": false,
            "scrollX": true,
            "destroy":true,
            "deferRender": true,
            "info": false,
            "lengthChange": false,
            "ordering": true,
            "searching": false,
            "order": [[ 0, "desc" ]],
            "pagingType": "simple",
            "pageLength":15,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_条",
                "sZeroRecords": "没有找到符合条件的数据",
                "sProcessing": "&lt;img src=’./loading.gif’ /&gt;",
                "sInfo": "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
                "sInfoEmpty": "木有记录",
                "sInfoFiltered": "(从 _MAX_ 条记录中过滤)",
                "sSearch": "搜索：",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                }
            }
        };



    getChannelId();
	// 填充
	function getChannelId() {
		$.ajax({
			url: Api.getUserList,
			type: 'post',
			success: function (data) {
				if (data.errorCode == 0) {
					// 长度为1时不是管理员
					if (data.data.length == 1) {
                        user.isAdmin = false;
                        user.channelList.push({
                            "channelId":data.data[0].channelId,
                            "channelName":data.data[0].channelName
                        });
                        user.curChannelId = data.data[0].channelId;
                        user.curBillId = data.data[0].billIdList[0];
                        fillDropdownList(data.data)
					}
					else{
                        user.isAdmin = true;
                        for(var i = 0,max = data.data.length;i < max; i++){
                            user.channelList.push({
                                "channelId":data.data[i].channelId,
                                "channelName":data.data[i].channelName
                            })
                        }
                        user.curChannelId = data.data[0].channelId;
                        user.curBillId = data.data[0].billIdList[0];
                        fillDropdownList(data.data)
					}
				} else {
					alert("获取用户列表时参数错误")
				}
			},
			error: function () {
				alert("获取列表失败")
			}
		})
	}
    // 填充下拉列表
    function fillDropdownList(data){
        if(user.isAdmin){
            dropdownAccountContainer.show();
            fillChannelDropDown(data)
        }else{
            dropdownAccountContainer.hide();
            // 只填充计费ID列表
            fillBillDropDown(data[0].billIdList)
        }
    }
    // 填充账号列表
    function fillChannelDropDown(data){
        var tempa = '',
            tempb = '';
        for(var i = 0,imax = data.length;i < imax;i++){
            tempa += "<option value=\"" + data[i].channelId +"\" >" + data[i].channelName + "</option>";
            user.channelList.push(data[i])  
        }
        dropdownAccount.html(tempa);
        dropdownAccount.change(function(e){
            var channelId = $(this).children('option:selected').val(),
                index = dropdownAccount[0].selectedIndex;
            user.curChannelId = channelId;
            fillBillDropDown(data[index].billIdList)
        });
        dropdownAccount[0].selectedIndex = 0;
        user.curChannelId = dropdownAccount[0].value;
        dropdownAccount.comboSelect();
        fillBillDropDown(data[dropdownAccount[0].selectedIndex].billIdList)
    }
    // 填充计费ID列表
    function fillBillDropDown(billIdList){
        var tempb = "<option value=\"0\" >全部</option>";
        dropdownBill.unbind('change');
        for(var i = 0,imax = billIdList.length;i < imax;i++){
            tempb += "<option value=\"" + billIdList[i] + "\" >" + billIdList[i] + "</option>"
        }
        dropdownBill.html(tempb);
        dropdownBill.change(function(){
            user.curBillId = $(this).children('option:selected').val();
            getDataList(user.timeStartFormatting,user.timeEndFormatting)
        });
        dropdownBill[0].selectedIndex = 0;
        user.curBillId = dropdownBill[0].value;
        dropdownBill.comboSelect();
        getDataList(user.timeStartFormatting,user.timeEndFormatting)
    }
    // 获取数据列表
	function getDataList(starttime,endtime){
		$.ajax({
			url:Api.getChannleList,
			type:'post',
            dataType:'json',
			data:{
				'dateBegin':starttime,
				'dateEnd':endtime,
				'channelId':user.curChannelId,
				'billId':(user.curBillId == 0?'':user.curBillId)
			},
			success:function(data){
				if(data.errorCode == 0){
                    // 将获数据结果转换
                    // var res = 
					// 填充到表格
					drawTable(nomalizeData('',data))
				}else{
					alert("获取数据列表时携带了不正确的参数")
				}
			},
			error:function(){
				alert("获取列表失败")
			}
		})
	}



	// 获取数据
	$('#dateSelect').daterangepicker({
	  	locale: {
	    	format: 'YYYY-MM-DD',
	    	// applyLabel:'确定',
	    	cancelLabel:'取消',
	    	customRangeLabel:"自定义"
	    },
	   "startDate":user.timeStart,
		"endDate":user.timeEnd,
		"minDate":getRelativeDate(-90),
		"maxDate":getRelativeDate(-1),
	    "ranges": {
        	"昨天": [
	            getRelativeDate(-1),
	            getRelativeDate(-1)
	        ],
	        "最近7天": [
	            getRelativeDate(-7),
	            getRelativeDate(-1)
	        ],
	       	"最近30天": [
	            getRelativeDate(-30),
	            getRelativeDate(-1)
	        ]
	    },
	    "autoApply": true
	}).on('apply.daterangepicker', function(ev, picker) {
        user.timeStart = picker.startDate._d;
        user.timeEnd = picker.endDate._d;
        user.timeStartFormatting = dataToYYYYMMDD(user.timeStart);
        user.timeEndFormatting = dataToYYYYMMDD(user.timeEnd);
		// 调用接口
		getDataList(user.timeStartFormatting,user.timeEndFormatting)
	});
	// 首屏获取数据

    // 检测是否命中缓存
    function transData(url){
        if(dataCache[url]){

        }
    }

    function drawTable(data){
        // try{
            if(echartTable){
                echartTable.init(data) 
            }else{
                echartTable =  new echartsOptions(echartContainer,data,echarts)
            }

           resetAll(data);
            $('.echartNav .nav').unbind('click');
            $('.echartNav .nav').click(function(){
                $('.echartNav .nav').removeClass('high');
                $(this).addClass('high');
                var id = $(this).attr('id');
                if (id == 'dayNav'){
                    user.curTab = 'byDay';
                    initTable(data);
                    echartTable.myChartDay.resize();
                    window.onresize = echartTable.myChartDay.resize
                } else {
                    user.curTab = 'byType';
                    initTable(data);
                    echartTable.myChartAd.resize();
                    window.onresize = echartTable.myChartAd.resize
                }
            });

            defaultReport.unbind('click');
            defaultReport.on("click",function(){
                closeCproTypeDetail(data)
            })
        // }catch(e){
        //     alert("绘制数据失败")
        // }
    }
    function resetAll(data) {
        echartNav.show();
        user.curTab = 'byDay';
        user.curType = '';
        tableByDayCon.show();
        tableByTypeCon.show();
        tableTypeByDayCon.show();
        $('.echartNav .nav').removeClass('high');
        $('.echartNav .dayNav').addClass('high');
        cproTypeNameTag.find("span").html('');
        cproTypeNameTag.hide();
         // 填充到表格
        initTable(data)
    }
    // ================= 表格处理 ==================
    // 初始化图表框架
    function initTable(tableData){
        // 填充到dashboard
        if(user.curTab == 'byDay' || user.curTab == 'byType'){
            zggzxl.html(tableData.dashboard.impressionBd);
            rpjggzxl.html(tableData.dashboard.impressionBdAvg);
            zdjl.html(tableData.dashboard.clickBd);
            rpjzdjl.html(tableData.dashboard.clickBdAvg);
            zdjl2.html(tableData.dashboard.clickBdRate + '%');
            rpjdjl2.html(tableData.dashboard.clickBdRateAvg + '%');
            ecpm.html(tableData.dashboard.ecpm + "元");
            rpjecpm.html(tableData.dashboard.ecpmAvg + "元");
            allincome.html(tableData.dashboard.earn + "元");
            rpjincome.html(tableData.dashboard.earnAvg + "元")
        }
        else if(user.curTab == 'typeDetail'){
            zggzxl.html(tableData.dashboardAdTypeByDay[user.curType].impressionBd);
            rpjggzxl.html(tableData.dashboardAdTypeByDay[user.curType].impressionBdAvg);
            zdjl.html(tableData.dashboardAdTypeByDay[user.curType].clickBd);
            rpjzdjl.html(tableData.dashboardAdTypeByDay[user.curType].clickBdAvg);
            zdjl2.html(tableData.dashboardAdTypeByDay[user.curType].clickBdRate + '%');
            rpjdjl2.html(tableData.dashboardAdTypeByDay[user.curType].clickBdRateAvg + '%');
            ecpm.html(tableData.dashboardAdTypeByDay[user.curType].ecpm + "元");
            rpjecpm.html(tableData.dashboardAdTypeByDay[user.curType].ecpmAvg + "元");
            allincome.html(tableData.dashboardAdTypeByDay[user.curType].earn + "元");
            rpjincome.html(tableData.dashboardAdTypeByDay[user.curType].earnAvg + "元")
        }
        // 填充到图表
        tableByDayCon.show();
        tableByTypeCon.show();
        tableTypeByDayCon.show();
        var toption = $.extend(true,{},tableOption);
        if(user.isAdmin == false) toption["autoWidth"] = false;
        if(user.curTab == 'byDay'){
            toption["columns"] = tableData.tableByDayColumn;
            toption.data = tableData.tableByDayList;
            tableByDay = tableByDayDom.dataTable(toption);
            tableTypeByDayCon.hide();
            tableByDayCon.show();
            tableByTypeCon.hide();
            $('.echartNav .nav').removeClass('high');
            $('.echartNav .dayNav').addClass('high');
            echartTable.element.find('.dayWrapper').show();
            echartTable.element.find('.adWrapper').hide()
        }
        else if(user.curTab == 'byType'){
            toption["columns"] = tableData.tableByTypeColumn;//tableData.tableByTypeColum
            toption.data = tableData.tableByTypeList;
            tableByType =  tableByTypeDom.dataTable(toption);
            tableTypeByDayCon.hide();
            tableByDayCon.hide();
            tableByTypeCon.show();
            tableByTypeDom.find('tr td').on('click',function (e) {
                var cproName = $(this).find(".adtype").text();
                if(cproName && cproName !='')
                    showCproTypeDetail(cproName,tableData)
            });
            $('.echartNav .nav').removeClass('high');
            $('.echartNav .adNav').addClass('high');
            echartTable.element.find('.adWrapper').show();
            echartTable.element.find('.dayWrapper').hide()
        }
        else if(user.curTab == 'typeDetail'){
            if(user.curType =="") return;
            toption["columns"] = tableData.tableAdTypeByDayColumn[user.curType][0];
            toption.data = tableData.tableAdTypeByDay[user.curType];
            tableTypeByDay = tableTypeByDayDom.dataTable(toption);
            tableTypeByDayCon.show();
            tableByDayCon.hide();
            tableByTypeCon.hide();
            echartNav.hide();
            echartTable.element.find('.dayWrapper').show();
            echartTable.element.find('.adWrapper').hide()
        }
    }


    // 展现广告详情页
    function showCproTypeDetail(cproName,data) {
        user.curTab = 'typeDetail';
        user.curType = cproName;
        // 显示面包屑
        if(echartTable){
            echartTable._detailCharts(cproName)
        }
        cproTypeNameTag.find("span").html(cproName);
        cproTypeNameTag.show();
        initTable(data)
    }
    function closeCproTypeDetail(data) {
        // if(user.curTab == 'typeDetail')
        user.curTab = 'byDay';
        // 隐藏面包屑
        if(echartTable){
            echartTable.init(data) 
        }
        initTable(data);
        cproTypeNameTag.hide();
        cproTypeNameTag.find("span").html('');
        echartNav.show()
    }

    // ================= 表格处理end ==================

    // 格式化数据
    function nomalizeData(url,data){
        // 整理好的按天和按广告类型整体的数据结构
        // 'tableList'数据
        var subDayObj =$.extend(true,{},normoliazedFormat);
        if(data.data.length == 0){
            subDayObj.isEmpty = true
        }
        for(var i=0;i<=data.data.length-1;i++){
            var dataOne  = data.data[i],
                billList = dataOne['billList'],
                date     = dataOne.date;

            // 图加 
            var billCount = {};
            subDayObj.dateList.push(date);
            for(var j=0;j<=billList.length-1;j++){
                var billOne = billList[j];
                for (var bill in billOne){
                    if ( bill == 'cproList' ) { 
                        var cproList = billOne[bill];
                        // 广告位
                        for( var k=0;k<=cproList.length-1;k++ ){
                            var cproObj = cproList[k];
                            var cproName = baseData.cproTypeMapping[cproObj.cproType];
                            // 如果有该广告类型，则将各项数值累加 
                            // 如果没有，则创建并初始化所有数据为0
                            if(!subDayObj.tableAdType.hasOwnProperty(cproName)){
                                subDayObj.tableAdType[cproName] = {};
                                for(var oob in cproObj){
                                    if(oob == 'cproType') continue;
                                    subDayObj.tableAdType[cproName][oob] = cproObj[oob]     
                                }
                            }else{
                                for(var x in cproObj){
                                    // 广告类型字段不累加
                                    if(x.toString() != 'cproType'){
                                        subDayObj.tableAdType[cproName][x] += cproObj[x]
                                    }
                                }
                            }

                            if(!subDayObj.dashboardAdTypeByDay.hasOwnProperty(cproName)){
                                subDayObj.dashboardAdTypeByDay[cproName] = {}
                            }  
                            if(!subDayObj.adTypeAll.hasOwnProperty(cproName)){
                                subDayObj.adTypeAll[cproName] = {}
                            }

                            subDayObj.dashboard.impressionBd += cproObj.impressionBd;
                            subDayObj.dashboard.clickBd += cproObj.clickBd;
                            subDayObj.dashboard.clickBdRate += cproObj.clickBdRate;
                            subDayObj.dashboard.ecpm += cproObj.ecpm;
                            subDayObj.dashboard.earn += cproObj.earn;

                            for(var cpro in cproObj){
                                // 广告位类型  ， eq 图加、插屏等
                                if ( cpro == 'cproType' ) continue;

                                var cproName = baseData.adTypeMapping[cpro],
                                    cproCount = cproObj[cpro];

                                if (cproName == '收入'){
                                    cproCount = parseFloat(parseFloat(cproCount / 100).toFixed(2))
                                }

                                if ( !subDayObj.unified.hasOwnProperty(cproName) ) {
                                    subDayObj.unified[cproName] = {
                                        'sub' : {},
                                        'value' : [],
                                        'key' : cpro
                                    }
                                }
                                var cproType = cproObj['cproType'],
                                    cproTypeName = baseData.cproTypeMapping[cproType];

                                if (!subDayObj.unified[cproName]['sub'].hasOwnProperty(cproTypeName)){
                                    subDayObj.unified[cproName]['sub'][cproTypeName] = {'sum':0,'list':new Array(data.data.length)}
                                }
                                if (!subDayObj.unified[cproName]['sub'][cproTypeName]['list'][i]) 
                                    subDayObj.unified[cproName]['sub'][cproTypeName]['list'][i] = 0;

                                subDayObj.unified[cproName]['sub'][cproTypeName]['list'][i] += cproCount;
                                subDayObj.unified[cproName]['sub'][cproTypeName]['sum'] += cproCount;

                                if (!billCount.hasOwnProperty(cproName)) billCount[cproName] = 0;
                                billCount[cproName] += cproCount
                            }
                        }
                    } else { // 计费名
                        // 计费名
                        var billName = baseData.adTypeMapping[bill],
                            billNameCount = billOne[bill];
                        // 
                        if ( !subDayObj.unified.hasOwnProperty(billName) ) {
                            subDayObj.unified[billName] = {
                                'sub' : {},
                                'value' : [],
                                'key' : bill
                            }
                        }
                        if (!billCount.hasOwnProperty(billName)) billCount[billName] = 0;
                        billCount[billName] += billNameCount
                    }
                }
            }

            for(s in subDayObj.unified){
                for(y in subDayObj.unified[s].sub){
                    for(z in subDayObj.unified[s].sub[y]){
                        if(subDayObj.unified[s].sub[y].list){
                            for(a = 0,amax = subDayObj.unified[s].sub[y].list.length;a< amax;a++){
                                if(!subDayObj.unified[s].sub[y].list[a]){
                                    subDayObj.unified[s].sub[y].list[a] = 0
                                }
                            }
                        }
                    }
                }
            }
            // billCount['收入'] = parseFloat(billCount['收入'] / 100).toFixed(2)
            for(var cproName in billCount){
                var val = billCount[cproName];
                if ( cproName == '点击率' ) {
                    val = billCount['广告展现量'] != 0 ? parseFloat( billCount['点击量'] / billCount['广告展现量'] ) * 100 : 0;
                    val = val.toFixed(2);
                    for ( var cpro in subDayObj.unified[cproName]['sub'] ) {
                        subDayObj.unified[cproName]['sub'][cpro]['list'][i] = subDayObj.unified['广告展现量']['sub'][cpro]['list'][i] != 0 ? (parseFloat(subDayObj.unified['点击量']['sub'][cpro]['list'][i] / subDayObj.unified['广告展现量']['sub'][cpro]['list'][i]) * 100).toFixed(2) : 0 
                    } 
                } else if ( cproName == '点击率（众盟）' ) {
                    val = billCount['广告展现量（众盟）'] !=0 ? parseFloat( billCount['点击量（众盟）'] / billCount['广告展现量（众盟）'] ) * 100 : 0;
                    val = val.toFixed(2);
                    for ( var cpro in subDayObj.unified[cproName]['sub'] ) {
                        subDayObj.unified[cproName]['sub'][cpro]['list'][i] = subDayObj.unified['广告展现量（众盟）']['sub'][cpro]['list'][i] != 0 ? (parseFloat(subDayObj.unified['点击量（众盟）']['sub'][cpro]['list'][i] / subDayObj.unified['广告展现量（众盟）']['sub'][cpro]['list'][i]) * 100).toFixed(2) : 0 
                    } 
                } else if ( cproName == '有效点击率（众盟）' ) {
                    val = billCount['有效广告展现量（众盟）'] != 0 ? parseFloat( billCount['有效点击量（众盟）'] / billCount['有效广告展现量（众盟）'] ) * 100 : 0;
                    val = val.toFixed(2);
                    for ( var cpro in subDayObj.unified[cproName]['sub'] ) {
                        subDayObj.unified[cproName]['sub'][cpro]['list'][i] = subDayObj.unified['有效广告展现量（众盟）']['sub'][cpro]['list'][i] != 0 ? (parseFloat(subDayObj.unified['有效点击量（众盟）']['sub'][cpro]['list'][i] / subDayObj.unified['有效广告展现量（众盟）']['sub'][cpro]['list'][i]) * 100).toFixed(2) : 0 
                    } 
                } else if ( cproName == 'eCPM' ) {
                    val = billCount['广告展现量'] != 0 ? parseFloat( billCount['收入'] / billCount['广告展现量'] ) * 1000 : 0;
                    val = val.toFixed(2);
                    // 按广告类型区分的ecpm = 分别将按广告类型区分的收入 / 按广告类型区分的广告展现量
                    for ( var cpro in subDayObj.unified[cproName]['sub'] ) {
                        subDayObj.unified[cproName]['sub'][cpro]['list'][i] = subDayObj.unified['广告展现量']['sub'][cpro]['list'][i] != 0 ? (parseFloat(subDayObj.unified['收入']['sub'][cpro]['list'][i] / subDayObj.unified['广告展现量']['sub'][cpro]['list'][i]) * 1000).toFixed(2) : 0 
                    } 
                } else if ( cproName == '页面cpm' ) {
                    val = parseFloat( billCount['页面cpm'] / billList.length ) / 100;
                    val = val.toFixed(2)
                } else if ( cproName == '收入' ) {
                    val = parseFloat(val).toFixed(2);
                    for ( var cpro in subDayObj.unified[cproName]['sub'] ) {
                        subDayObj.unified[cproName]['sub'][cpro]['list'][i] = subDayObj.unified[cproName]['sub'][cpro]['list'][i].toFixed(2);
                        subDayObj.unified[cproName]['sub'][cpro]['sum'] = parseFloat(subDayObj.unified[cproName]['sub'][cpro]['sum']).toFixed(2)
                    } 
                }
                subDayObj.unified[cproName]['value'].push(val)
            }
        }    
        // dashboard
        var days = data.data.length;
        if(days > 0){
            subDayObj.dashboard.impressionBdAvg = (parseFloat(subDayObj.dashboard.impressionBd/days)).toFixed();
            subDayObj.dashboard.clickBdAvg = (parseFloat(subDayObj.dashboard.clickBd/days)).toFixed(2);
            if(subDayObj.dashboard.impressionBd != 0){
                subDayObj.dashboard.clickBdRate = (parseFloat(subDayObj.dashboard.clickBd/subDayObj.dashboard.impressionBd)*100).toFixed(2)
            }else{
                subDayObj.dashboard.clickBdRate = 0
            }
            subDayObj.dashboard.clickBdRateAvg = (parseFloat(subDayObj.dashboard.clickBdRate/days)).toFixed(2);
            subDayObj.dashboard.earn = (parseFloat(subDayObj.dashboard.earn/100)).toFixed(2);
            if(subDayObj.dashboard.impressionBd != 0){
                subDayObj.dashboard.ecpm = (parseFloat((subDayObj.dashboard.earn/subDayObj.dashboard.impressionBd)*1000)).toFixed(2) 
            }else{
                subDayObj.dashboard.ecpm = 0
            }
            subDayObj.dashboard.ecpmAvg = (parseFloat(subDayObj.dashboard.ecpm/days)).toFixed(2);
            subDayObj.dashboard.earnAvg = (parseFloat(subDayObj.dashboard.earn/days)).toFixed(2)
        }
        
        // ======================================   广告类型表  ==========================================

        
        // 循环平均点击率/点击率众盟/有效点击率
        for(y in subDayObj.tableAdType){
            if(subDayObj.tableAdType[y]['click']){
                // 点击率
                var clickRate = 0;
                if(subDayObj.tableAdType[y]['click'] != 0){
                    clickRate = parseFloat(subDayObj.tableAdType[y]['click']/subDayObj.tableAdType[y]['impression'])*100;
                    clickRate = clickRate.toFixed(2)
                }
                subDayObj.tableAdType[y]['clickRate'] = clickRate + '%'
            }
            if(subDayObj.tableAdType[y]['clickBd']){
                // 众盟点击率
                var clickBdRate = 0;
                if(subDayObj.tableAdType[y]['clickBd'] != 0){
                    clickBdRate = parseFloat(subDayObj.tableAdType[y]['clickBd']/subDayObj.tableAdType[y]['impressionBd'])*100;
                    clickBdRate = clickBdRate.toFixed(2)
                }
                subDayObj.tableAdType[y]['clickBdRate'] = clickBdRate + '%'
            }
            if(subDayObj.tableAdType[y]['click'] && subDayObj.tableAdType[y]['impression']){
                //有效点击率
                var clickValidRate = 0;
                if(subDayObj.tableAdType[y]['clickValid']!=0){
                    clickValidRate = parseFloat(subDayObj.tableAdType[y]['clickValid']/subDayObj.tableAdType[y]['impressionValid'])*100;
                    clickValidRate = clickValidRate.toFixed(2)
                }
                subDayObj.tableAdType[y]['clickValidRate'] = clickValidRate + '%'
            }
            if(subDayObj.tableAdType[y]['earn']){
                //有效点击率
                var earn = parseFloat(subDayObj.tableAdType[y]['earn']/100);
                    earn = earn.toFixed(2);
                subDayObj.tableAdType[y]['earn'] = earn
            }
            if(subDayObj.tableAdType[y]['ecpm']){
                //有效点击率
                var ecpm = parseFloat(subDayObj.tableAdType[y]['earn']*1000/subDayObj.tableAdType[y]['impressionBd']);
                    ecpm = ecpm.toFixed(2);
                subDayObj.tableAdType[y]['ecpm'] = ecpm
            }
            var rowType = [];
                rowType.push("<span class=\"adtype\">" + y.toString() + "</span>");
            if(user.isAdmin){
                for(var x = 0,xmax = baseData.cproTypeTitleMatch.admin.length;x<xmax;x++){
                    rowType.push(subDayObj.tableAdType[y][baseData.cproTypeTitleMatch.admin[x]])
                }
            }else{
                for(var x = 0,xmax = baseData.cproTypeTitleMatch.channel.length;x<xmax;x++){
                    rowType.push(subDayObj.tableAdType[y][baseData.cproTypeTitleMatch.channel[x]])
                }
            }
            subDayObj.tableByTypeList.push(rowType)
        }
        
        if(user.isAdmin){
            subDayObj.tableByTypeColumn.push({'title':"广告类型",'width':'150px'});
            for(var a = 0,amax = baseData.cproTypeTitle.admin.length;a < amax;a++){
                subDayObj.tableByTypeColumn.push({'title':baseData.cproTypeTitle.admin[a],'width':'150px'})
            }
        }else{
            subDayObj.tableByTypeColumn.push({'title':"广告类型"});
            for(var b = 0,bmax = baseData.cproTypeTitle.channel.length;b < bmax;b++){
                subDayObj.tableByTypeColumn.push({'title':baseData.cproTypeTitle.channel[b]})
            }
        }
        // ======================================   广告类型表end  ==========================================
        


        // ======================================   广告按天表 ==========================================
        
        // if(data.data.length <= 0){
        //     subDayObj.tableByDayColumn.push({'title':"日期",'width':'150px'})
        //     for(var s in baseData.adTypeMapping){
        //         subDayObj.tableByDayColumn.push({'title':baseData.adTypeMapping[s].toString(),'width':'150px'})
        //     }
        // }else{
            if(user.isAdmin){
                subDayObj.tableByDayColumn.push({'title':"日期",'width':'150px'});
                for( x = 0,xmax = baseData.adByDayTable.admin.length;x<xmax;x++){
                    subDayObj.tableByDayColumn.push({'title':baseData.adByDayTable.admin[x],'width':'150px'})
                }
            }else{
                subDayObj.tableByDayColumn.push({'title':"日期"});
                for(var x = 0,xmax = baseData.adByDayTable.channel.length;x<xmax;x++){
                    subDayObj.tableByDayColumn.push({'title':baseData.adByDayTable.channel[x]})
                }
            }
        // }
       
         for(var k = 0,kmax = subDayObj.dateList.length;k < kmax;k++){
            var rowDay = [];
            var rowTypeByDay = [];
            rowDay.push(subDayObj.dateList[k]);
            if(user.isAdmin){
                for(var x = 0,xmax = baseData.adByDayTable.admin.length;x<xmax;x++){
                    if(baseData.adByDayTable.admin[x].toString().indexOf('率') >= 0){
                        rowDay.push(subDayObj.unified[baseData.adByDayTable.admin[x]].value[k]+"%")
                    }else{
                        rowDay.push(subDayObj.unified[baseData.adByDayTable.admin[x]].value[k])
                    } 
                }
            }else{
                for(var x = 0,xmax = baseData.adByDayTable.channel.length;x<xmax;x++){
                    if(baseData.adByDayTable.channel[x].toString().indexOf('率') >= 0){
                        rowDay.push(subDayObj.unified[baseData.adByDayTable.channel[x]].value[k]+"%")
                    }else{
                        rowDay.push(subDayObj.unified[baseData.adByDayTable.channel[x]].value[k])
                    } 
                }
            }   
            subDayObj.tableByDayList.push(rowDay)
        }



        for(y in subDayObj.tableAdType){
            subDayObj.tableAdTypeByDay[y] = [];
            subDayObj.tableAdTypeByDayColumn[y] = [];

            for(var k = 0,kmax = subDayObj.dateList.length;k < kmax;k++){
                var row = [],rowColumn = [];
                    row.push(subDayObj.dateList[k]);
                user.isAdmin?rowColumn.push({'title':"日期",'width':'150px'}):rowColumn.push({'title':"日期"});
                if(user.isAdmin){
                    for(var x = 0,xmax = baseData.typeByDayTable.admin.length;x<xmax;x++){
                        rowColumn.push({'title':baseData.typeByDayTable.admin[x],'width':'150px'});
                        if(baseData.typeByDayTable.admin[x].toString().indexOf('率') >= 0){
                            row.push(subDayObj.unified[baseData.typeByDayTable.admin[x]].sub[y].list[k]+"%")
                        }else{
                            row.push(subDayObj.unified[baseData.typeByDayTable.admin[x]].sub[y].list[k])
                        } 
                    }
                }else{
                    for(var x = 0,xmax = baseData.typeByDayTable.channel.length;x<xmax;x++){
                        rowColumn.push({'title':baseData.typeByDayTable.channel[x]});
                        if(baseData.typeByDayTable.channel[x].toString().indexOf('率') >= 0){
                            row.push(subDayObj.unified[baseData.typeByDayTable.channel[x]].sub[y].list[k]+"%")
                        }else{
                            row.push(subDayObj.unified[baseData.typeByDayTable.channel[x]].sub[y].list[k])
                        } 
                    }
                }   

                subDayObj.tableAdTypeByDay[y].push(row);
                subDayObj.tableAdTypeByDayColumn[y].push(rowColumn)
            }
        }
        for(y in subDayObj.adTypeAll){
            for(s in subDayObj.unified){
                if(subDayObj.unified[s].sub[y]){
                    subDayObj.adTypeAll[y][s] = subDayObj.unified[s].sub[y].sum
                }
            }
        }
        for(x in subDayObj.adTypeAll){
            if(days > 0){
                subDayObj.dashboardAdTypeByDay[x].impressionBd =  subDayObj.adTypeAll[x]["广告展现量"];    //总展现
                subDayObj.dashboardAdTypeByDay[x].impressionBdAvg =  (parseFloat(subDayObj.dashboardAdTypeByDay[x].impressionBd/days)).toFixed(); //日均总展现
                subDayObj.dashboardAdTypeByDay[x].clickBd = subDayObj.adTypeAll[x]["点击量"];//总点击
                subDayObj.dashboardAdTypeByDay[x].clickBdAvg = (parseFloat(subDayObj.adTypeAll[x]["点击量"]/days)).toFixed(); //日均总点击
                subDayObj.dashboardAdTypeByDay[x].clickBdRate = (parseFloat(subDayObj.adTypeAll[x]["点击量"]/subDayObj.adTypeAll[x]["广告展现量"])*100).toFixed(2); //日均总展现//总点击率
                subDayObj.dashboardAdTypeByDay[x].clickBdRateAvg = (parseFloat(subDayObj.dashboardAdTypeByDay[x].clickBdRate/days)).toFixed(2);//日均点击率
                subDayObj.dashboardAdTypeByDay[x].earn = parseFloat(subDayObj.adTypeAll[x]["收入"]).toFixed(2);//收入
                subDayObj.dashboardAdTypeByDay[x].ecpm =  (parseFloat((subDayObj.adTypeAll[x]["收入"]/subDayObj.adTypeAll[x]["广告展现量"])*1000)).toFixed(2); //ecpm
                subDayObj.dashboardAdTypeByDay[x].ecpmAvg = (parseFloat(subDayObj.dashboardAdTypeByDay[x].ecpm/days)).toFixed(2); //日均ecpm
                subDayObj.dashboardAdTypeByDay[x].earnAvg = (parseFloat(subDayObj.dashboardAdTypeByDay[x].earn/days)).toFixed(2)//日均收入
            }
        }
        // ======================================   广告按天表end  ==========================================
        dataCache[url] = subDayObj;
        return subDayObj
    }

    $(window).resize(function(){    
        $('.main_show_row div').css('height','auto');
        var  arr1=$('.main_show_row_1').outerHeight();
        var  arr2=$('.main_show_row_2').outerHeight();
        var  arr3=$('.main_show_row_3').outerHeight();
        var  arr4=$('.main_show_row_4').outerHeight();
        var  arr5=$('.main_show_row_5').outerHeight();      
        var arr=[arr1,arr2,arr3,arr4,arr5];
        for(var i=0;i<arr.length;i++){          
            if(arr[i]>88){
                $('.main_show_row div').css('height',arr[i]+'px');
            }
        }       
    })

}(jQuery);